package com.iflytek.cosmo.ocr.support.license.server.v2;

import cn.hutool.core.util.StrUtil;
import com.iflytek.cosmo.ocr.common.utils.ComputerIdentifierExtractor;
import com.iflytek.cosmo.ocr.support.license.LicenseVersion;
import com.iflytek.cosmo.ocr.support.license.server.ServerLicense;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2021/6/29
 */
@Data
public class ServerLicenseV2 extends ServerLicense {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    /** 服务器标识 */
    private String machineId;

    public ServerLicenseV2() {
        this.version = LicenseVersion.V2.getCode();
    }

    public ServerLicenseV2(String license) {
        super(license);
        this.machineId = license.substring(license.indexOf(SUBCLASS_SEPARATOR) + 1);
    }

    public boolean valid() {
        boolean superValid = super.valid();
        if (!superValid) {
            return false;
        }
        if (StrUtil.isBlank(this.machineId)) {
            logger.info("授权码中未包含machineId信息");
            return false;
        }

        // 读取本机machineId信息
        try {
            String localMachinedId = ComputerIdentifierExtractor.getLinuxMachinedId();
            logger.info("本机machineId: {}", localMachinedId);
            return this.machineId.equalsIgnoreCase(localMachinedId);
        }
        catch (Exception e) {
            logger.warn("无法读取本机machineId", e);
            return false;
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(super.toString());
        sb.append(this.machineId);

        return sb.toString();
    }
}
